/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ActualizacionPrecios.java
 *
 * Created on 27-jun-2013, 11:45:40
 */
package ventasdia;

import com.util.Fecha;
import com.util.database.UtilidadesBaseDatos;
import com.util.dialog.UtilidadesCuadroDialogo;
import com.util.files.Ficheros;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFileChooser;
import org.jdesktop.application.Action;
import ventasdia.modelo.ArticuloVO;

/**
 *
 * @author Usuario
 */
public class ActualizacionPrecios extends javax.swing.JDialog {
   

    /**
     * Constructor
     * @param parent 
     */
    ActualizacionPrecios(java.awt.Frame parent) {
        super(parent);
        initComponents();
        fecha = new Fecha();
        rutadescarga = Variables.PREFIJOURL + fecha.getStrFechaFormatoAmericano() + Variables.SUFIJOURL;
        rutaact = Variables.PREFIJORUTAACTU + fecha.getStrFechaFormatoAmericano() + Variables.SUFIJORUTAACTU;
        rutaActualizacion = Variables.RUTABDACTU;
        hayactualizacion = false;
        resultadoActualizacion = new StringBuffer();
        resultadoActualizacion.append("<html><head><title>Actualizacion "+fecha.getStrFechaFormatoAmericano()+"</title></head></body>");
        resultadoActualizacion.append("<table border=1>");
        resultadoActualizacion.append("<tr><th>Codigo</th><th>Descripción</th><th>PVP Nuevo</th><th>PVP Anterior</th><tr>");
      
        
        iniciar_Actualizacion();



    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ventasdia.VentasDiaApp.class).getContext().getResourceMap(ActualizacionPrecios.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jTextField2.setText(resourceMap.getString("jTextField2.text")); // NOI18N
        jTextField2.setName("jTextField2"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jTextField3.setText(resourceMap.getString("jTextField3.text")); // NOI18N
        jTextField3.setName("jTextField3"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jTextField4.setText(resourceMap.getString("jTextField4.text")); // NOI18N
        jTextField4.setName("jTextField4"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jTextField5.setText(resourceMap.getString("jTextField5.text")); // NOI18N
        jTextField5.setName("jTextField5"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(ventasdia.VentasDiaApp.class).getContext().getActionMap(ActualizacionPrecios.class, this);
        jButton3.setAction(actionMap.get("btn_cargar_Siguiente")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N

        jButton4.setAction(actionMap.get("btnCerrar_Actualizacion")); // NOI18N
        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N

        jButton5.setAction(actionMap.get("btn_guardar_actualizacion")); // NOI18N
        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N

        jProgressBar1.setName("jProgressBar1"); // NOI18N
        jProgressBar1.setStringPainted(true);

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jButton1.setAction(actionMap.get("mostratar_cambios")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(19, 19, 19)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField5)
                                    .addComponent(jTextField4)
                                    .addComponent(jTextField3)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(52, 52, 52))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton3)
                                .addGap(111, 111, 111))))
                    .addComponent(jLabel7)
                    .addComponent(jLabel2)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 214, Short.MAX_VALUE)
                        .addComponent(jButton4)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(58, 58, 58)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton5))
                .addGap(99, 99, 99)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton1))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Actions
    @Action
    public void btnCerrar_Actualizacion() {
        this.dispose();
    }

    @Action
    public void seleccionarbdActualizacion() {
        rutaActualizacion = UtilidadesCuadroDialogo.abrirSelectorArchivo(JFileChooser.FILES_ONLY, "Seleccione base de datos...");

    }

    @Action
    public void btn_cargarDatosActualizacion() {
        String sql = "select * from ARTI";
        listaDeArticulos = UtilidadesBaseDatos.realizarConsultaListaArticuloVO(Variables.d_actualizacion+"\\"+rutaActualizacion, sql);
        limpiarLista();
    }

    @Action
    public void btn_cargar_Siguiente() {
        posicion++;
        cargar_articulo();
        if ((posicion + 1) == listaDeArticulos.size()) {
            jButton3.setEnabled(false);
        }

    }

    @Action
    public void btn_guardar_actualizacion() {
        ArticuloVO a = listaDeArticulos.get(posicion);
        String pvp = jTextField5.getText();
        a.precioCesion = (a.pvp - (a.pvp * (float) 0.085)) / (float) 1.2275;
        Fecha marcaDeTiempo = new Fecha();
        Float ivamed = a.precioCesion*0.2275f;
        String sql = "update artículos set Pvp1=" + pvp + ", Pvp2=" + pvp + ", Pvp3=" + pvp + ", Pvp4=" + pvp + ", Coste=" + a.precioCesion + ", Ivamed="+ivamed+", Costemed="+a.precioCesion+", Comen2='Mod" + marcaDeTiempo.getStrFormatoDDMMAAA() + "' where Codprov='" + a.codigo + "'";
        UtilidadesBaseDatos.actualizar(sql);
       
        resultadoActualizacion.append("<tr><td>"+a.codigo+"</td><td>"+a.descripcion+"</td><td>"+pvp+"</td><td>"+a.pvpAnt+"</td><tr>");
         if ((posicion + 1) == listaDeArticulos.size()) {
            jButton3.setEnabled(false);
        }
        if (jButton3.isEnabled()) {
            btn_cargar_Siguiente();
        } 
    }

    // Fin Actions
    private void limpiarLista() {
        progreso = new Integer(0);
        jProgressBar1.setVisible(true);
        habilitar_componentes(false);

        hiloLista = new ThreadLista();
        hiloLista.start();
    }

    private void cargar_articulo() {
        ArticuloVO a = listaDeArticulos.get(posicion);
        jLabel2.setText("Artículo " + (posicion + 1) + " / " + listaDeArticulos.size());
        jTextField2.setText(a.codigo);
        jTextField3.setText(a.descripcion);
        jTextField4.setText(a.pvpAnt.toString());
        jTextField5.setText(a.pvp.toString());


    }

    private void habilitar_componentes(boolean b) {

        jTextField2.setEnabled(b);
        jTextField3.setEnabled(b);
        jTextField4.setEnabled(b);
        jTextField5.setEnabled(b);

        jButton3.setEnabled(b);
        jButton4.setEnabled(b);
        jButton5.setEnabled(b);

    }

    private void iniciar_Actualizacion() {
        hiloDescarga = new ThreadDescarga();
        hiloDescarga.start();
        hiloDescompresion = new ThreadDescomprimir();
        hiloDescompresion.start();
    }

    @Action
    public void mostratar_cambios() throws IOException {
        
        resultadoActualizacion.append("</table></body></html>");
        Ficheros.escribir_fichero_texto(Variables.d_actualizacion_resultado+"\\"+"actu"+fecha.getStrFechaFormatoAmericano()+".htm", resultadoActualizacion);
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " +Variables.d_actualizacion_resultado+"\\"+ "actu"+fecha.getStrFechaFormatoAmericano()+".htm");
        
        
    }
    /**
     * @param args the command line arguments
     */
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    //</editor-fold>

    /* Create and display the dialog */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration//GEN-END:variables
    private String rutaActualizacion;
    public List<ArticuloVO> listaDeArticulos;
    private int posicion = -1;
    private Fecha fecha;
    private Thread hiloLista;
    private Thread hiloDescarga;
    private Thread hiloDescompresion;
    private Integer progreso;
    private String rutadescarga;
    private String rutaact;
    private boolean hayactualizacion;
    private StringBuffer resultadoActualizacion;

    public class ThreadDescomprimir extends Thread {

        public void run() {
            while (hiloDescarga != null) {
            }
            if (!hayactualizacion) {
                jLabel7.setText("No hay actualizacion, se procesará la última encontrada");
                btn_cargarDatosActualizacion();
            } else {
                File f = new File(Variables.d_actualizacion+"\\"+rutaact);
                if (f.exists()) {
                    jLabel7.setText("Iniciando descompresión");
                    Ficheros.descomprimirFichero(Variables.d_actualizacion+"\\"+rutaact);
                    jLabel7.setText("Descompresión finalizada");
                    btn_cargarDatosActualizacion();
                } else {
                    jLabel7.setText("No existen actualizaciones");
                }
            }

            hiloDescompresion = null;


        }
    }

    public class ThreadDescarga extends Thread {

        public void run() {

            jLabel7.setText("Comprobando si existen actualizaciones...");
            jProgressBar1.setValue(0);
            // 1º Comprobación local
            File f = new File(Variables.d_actualizacion+"\\"+rutaact);
            if (!f.exists()) {
                jLabel7.setText("Descargando actualizacion");
                hayactualizacion = Ficheros.descargarFichero(rutadescarga, Variables.d_actualizacion+"\\"+rutaact);
            } else {
                jLabel7.setText("Existe Actualización local de hoy");
                hayactualizacion = true;
            }
            jProgressBar1.setValue(100);

            hiloDescarga = null;
        }
    }

    public class ThreadLista extends Thread {

        public void run() {
            List<ArticuloVO> retorno = new ArrayList<ArticuloVO>();
            jLabel7.setText("Organizando los articulos a actualizar");

            int it = 0;
            for (ArticuloVO a : listaDeArticulos) {
                progreso = (it * 100 / listaDeArticulos.size()) + 1;
                jProgressBar1.setValue(progreso);

                it++;
                String sql = "Select Pvp1 from artículos where Codprov ='" + a.codigo + "' and FamSub like '%TA1%'";
                String r = UtilidadesBaseDatos.realizarConsultastr(sql);
                if (r != null && !r.isEmpty()) {
                    a.pvpAnt = new Float(r);
                    if (!a.pvp.equals(a.pvpAnt)) {
                        retorno.add(a);
                    }
                }
            }
            listaDeArticulos = new ArrayList<ArticuloVO>();
            listaDeArticulos.addAll(retorno);
            habilitar_componentes(true);
            if (jButton3.isEnabled()) {
                btn_cargar_Siguiente();
            }
            jLabel7.setText("Ahora puede comenzar a actulizar los precios");
            hiloLista = null;
        }
    }
}